package com.sj.parksdk.fragment.pay;

import android.widget.RadioGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.sj.parksdk.R;
import com.sj.parksdk.R2;
import com.sj.parksdk.adapter.base.delegate.SimpleDelegateAdapter;
import com.sj.parksdk.core.BaseFragment;
import com.sj.parksdk.net.http.MyNetApi;
import com.sj.parksdk.net.http.callback.TipRequestCallBack;
import com.sj.parksdk.net.request.MGetRequest;
import com.sj.parksdk.net.result.databean.Data_PayRecord;
import com.sj.parksdk.setting.Extras;
import com.sj.parksdk.utils.RefreshState;
import com.sj.parksdk.utils.Utils;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.statelayout.StatefulLayout;
import com.xuexiang.xutil.data.DateUtils;

import java.text.SimpleDateFormat;

import butterknife.BindView;

@Page(name = "缴费记录 ")
public class FragmentPayRecord extends BaseFragment {
    @BindView(R2.id.rg_date_type)
    RadioGroup rgDateType;
    @BindView(R2.id.recycler)
    RecyclerView recycler;
    @BindView(R2.id.ll_state)
    StatefulLayout llState;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;

    private SimpleDelegateAdapter adapter;

    @Override
    protected int getLayoutId() {
        return R.layout.parksdk_fragment_pay_record;
    }

    @Override
    protected void initViews() {
        initRadioGroup();
        initAdapter();
    }

    @Override
    protected void initData() {
        rgDateType.check(R.id.rb_all);
    }

    private void initAdapter() {
        adapter = new SimpleDelegateAdapter<Data_PayRecord>(R.layout.parksdk_adapter_pay_record, new LinearLayoutHelper()) {
            @Override
            protected void bindData(@NonNull RecyclerViewHolder holder, int position, Data_PayRecord item) {
                holder.text(R.id.tv_name, item.getCarNo());
                holder.text(R.id.tv_order_time, "支付时间：" + DateUtils.millis2String(item.getPaidTime(), new SimpleDateFormat("yyyy-MM-dd HH:mm:SS")));
                holder.text(R.id.tv_order_number, "订单号：" + item.getOrderNo());
                holder.text(R.id.tv_price, Utils.getPriceHtml(item.getTotalFee().toString(), 2));
                holder.click(R.id.ll_item, v -> gotoPayRecordDetail(item.getTradeNo()));
            }
        };
        WidgetUtils.initRecyclerView(recycler, DensityUtils.dp2px(10), ResUtils.getColor(R.color.base_bg_color));
        recycler.setAdapter(adapter);
    }

    private void gotoPayRecordDetail(String tradesNo) {
        openPage(FragmentPayRecordDetail.class, Extras.BASE_CODE,tradesNo);
    }

    private long startTime = 0;
    private long endTime = DateUtils.getNowMills() / 1000;

    private void initRadioGroup() {
        rgDateType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_all) {
                    startTime = 0;
                } else if (checkedId == R.id.rb_one_year) {
                    startTime = DateUtils.date2Millis(DateUtils.nMonthsAfterToday(-12)) / 1000;
                } else if (checkedId == R.id.rb_half_year) {
                    startTime = DateUtils.date2Millis(DateUtils.nMonthsAfterToday(-6)) / 1000;
                } else if (checkedId == R.id.rb_month) {
                    startTime = DateUtils.date2Millis(DateUtils.nMonthsAfterToday(-1)) / 1000;
                }
                refresh.autoRefresh();
            }
        });
    }

    private int pageIndex = 1;

    private void queryRecord(int flag) {
        new MGetRequest(MyNetApi.ORDER_PAY_RECORD)
                .user()
                .params(MyNetApi.PageParam.pageSize, 10)
                .params(MyNetApi.PageParam.pageIndex, pageIndex)
                .params(MyNetApi.PageParam.endTime, endTime)
                .params(MyNetApi.PageParam.startTime, startTime)
                .execute(new TipRequestCallBack<Data_PayRecord>() {
                    @Override
                    public void onSuccess(Data_PayRecord response) throws Throwable {
                        queryRecordSuccess(response, flag);
                    }

                    @Override
                    public void onError(ApiException e) {
                        llState.showError(null);
                    }
                });

    }

    private void queryRecordSuccess(Data_PayRecord response, int flag) {
        if(response.getItems() == null && flag == RefreshState.refresh){
            llState.showCustom(emptyStatus());
            return;
        }
        switch (flag) {
            case RefreshState.refresh:
                if (response.getItems().size() == 0) llState.showCustom(emptyStatus());
                else llState.showContent();
                adapter.refresh(response.getItems());
                refresh.finishRefresh();
                if (response.getTotal() == response.getItems().size()) refresh.setNoMoreData(true);
                break;
            case RefreshState.more:
                adapter.loadMore(response.getItems());
                if (response.getTotal() == adapter.getData().size()) {
                    refresh.finishLoadMoreWithNoMoreData();
                    break;
                }
                refresh.finishLoadMore();
                break;
        }
    }

    @Override
    protected void initListeners() {
        refresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageIndex++;
                queryRecord(RefreshState.more);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageIndex = 1;
                queryRecord(RefreshState.refresh);
            }
        });
    }
}
